const Koa = require('koa');
const cors = require('@koa/cors');
const session = require('koa-session');
const app = new Koa();

app.keys = ['some secret hurr'];

const CONFIG = {
  key: 'koa:sess', //默认
  maxAge: 86400000,//[需要设置]
  overwrite: true,//覆盖，无效
  httpOnly: true,
  signed: true,//签名，默认true
  rolling: false,  //每次请求强制设置session
  renew: true,//快过期的时候的请求设置session[需要设置]
};

app.use(cors({
  origin: function (ctx) {
      if (ctx.url === '/cors') {
          return "*"; // 允许来自所有域名请求
      }
      return 'http://localhost:8080';
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'], //设置允许的HTTP请求类型
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));


app.use(session(CONFIG, app));

app.use(ctx => {
  // ignore favicon
  if (ctx.path === '/favicon.ico') return;

  if (ctx.path === '/login') {
    let n = ctx.session.views || 0;
    ctx.session.views = ++n;
    ctx.body = {
      n
    };
  }

});

app.listen(3000);
console.log('listening on port 3000');
